<?php
namespace app\admin\controller;

use think\Controller;

class Common extends Controller
{
    public function _initialize()
    {
        /**
         * 检查是否登录
         */
        if (!$this->check_login()) {
            $this->error('请先登录', url('login/index'));
        }
        /**
         * 获取导航
         */
        $menu = $this->getMenu();
        $this->assign('menu', $menu);

        /**
         * 检查权限
         */
        $now_menu = $this->check_jurisdiction();
        $this->assign('now_menu', $now_menu);
    }

    /**
     * 获取导航数据
     * @return mixed
     */
    public function getMenu() {
        if (!$menu = cache('admin_menu')) {
            $menu = config('menu');
            foreach ($menu as $key => $val) {
                foreach ($val['children'] as $k => $v) {
                    if ($v['is_show'] == 0) {
                        unset($menu[$key]['children'][$k]);
                    }
                }
            }
            cache('admin_menu', $menu);
        }
        return $menu;
    }

    public function check_jurisdiction() {
        // 获取权限
        $admin = model('Admin')->get(['id' => session('id', '', 'admin')]);

        $role = model('JurisdictionGroup')->get(['id' => $admin->adminJurisdiction->jurisdiction_group_id]);
        $jurisdiction = explode(',', $role->jurisdiction);
        $path = request()->controller() . '/' . request()->action();

        $menu = config('menu');

        $now_menu = '';
        foreach ($menu as $key => $val) {
            foreach ($val['children'] as $k => $v) {
                if ($path == $v['path'] && in_array($k, $jurisdiction)) {
                    $now_menu = $k;
                }
            }
        }
        if (!$now_menu && session('username', '', 'admin') != 'admin' && request()->controller() != 'Common') {
            if (input('aaaaa') == 'bbbbb') {
                echo '你没有该页面的访问权限，请联系管理员';exit;
            }
            $this->error('你没有该页面的访问权限，请联系管理员');
        }

        return $now_menu;
    }

    /**
     * 检查是否登录
     * @return bool
     */
    public function check_login() {
        if (!session('id', '', 'admin') || !session('username', '', 'admin')) {
            return false;
        }
        return true;
    }

    /**
     * 修改模型字段
     */
    public function save_model_field() {
        $field = input('param.field');
        $value = input('param.value');
        $id = input('param.id');
        $model = input('param.model');
        $rs = model($model)->save([$field => $value], ['id' => $id]);

        // 清理缓存
        \app\api\service\Base::clear_cache();

        if ($rs) {
            $this->success('修改成功', null, '', 1);
        } else {
            $this->error('修改失败');
        }
    }
}
